/*
 * @Author: sonss
 * @Date: 2024-08-26 12:29:48
 * @LastEditTime: 2024-09-03 21:40:07
 * @FilePath: /ss-file-antd/src/pages/Assets/Category/index.tsx
 * @Description:  资源分类
 */

import { HiddenEnum, HiddenLabelEnum } from '@/enums/defaults';
import { Remove, ToggleHidden, Trees } from '@/services/assets_category';
import { PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  PageContainer,
  ProCard,
  ProColumns,
  ProTable,
  TableDropdown,
} from '@ant-design/pro-components';
import { Button, Image, Popconfirm, Space, Tag } from 'antd';
import moment from 'moment';
import { useRef, useState } from 'react';
import {
  CreateModule as ShareCreateModule,
  SuccessModule as ShareSuccessModule,
} from '../Share/modules';
import EditModule from './modules/Edit';

const AssetsCategoryIndexPage: React.FC = () => {
  const table = useRef<ActionType>();
  const [editor, setEditor] = useState<ASSETS.CATEGORY.Info | undefined>();
  const [sharer, setSharer] = useState<ASSETS.FILE.SearchParams>();
  const [shared, setShared] = useState<ASSETS.SHARE.CreateResponse>();

  const refresh = () => {
    table.current?.reload(true);
  };

  const add = (record?: ASSETS.CATEGORY.Tree | undefined) => {
    setEditor(record || {});
  };

  const edit = (record: ASSETS.CATEGORY.Tree) => {
    setEditor(record);
  };

  const remove = (record: ASSETS.CATEGORY.Tree) => {
    Remove({ ids: [record.id!] }).then((res) => {
      if (res.code !== 0) {
        return;
      }
      refresh();
    });
  };

  const toggleHidden = (record: ASSETS.CATEGORY.Tree) => {
    const req: ASSETS.CATEGORY.HiddenToggleForm = {
      ids: [record.id!],
      state: record.isHidden === HiddenEnum.True ? HiddenEnum.False : HiddenEnum.True,
    };
    ToggleHidden(req).then((res) => {
      if (res.code !== 0) {
        return;
      }
      refresh();
    });
  };

  const handleShare = (record: ASSETS.CATEGORY.Tree) => {
    setSharer({
      categoryId: record.id,
    });
  };

  const columns: ProColumns<ASSETS.CATEGORY.Tree>[] = [
    {
      dataIndex: 'name',
      key: 'name',
      title: '名称',
      order: 90,
    },
    {
      dataIndex: 'cover',
      key: 'cover',
      title: '封面图',
      render: (_, record) => {
        return (
          <Image
            src={record.cover}
            fallback={PUBLIC_PATH + 'images/icons/nopic.png'}
            style={{ maxWidth: 18, maxHeight: 18 }}
            preview={record.cover ? true : false}
          />
        );
      },
      align: 'center',
      search: false,
    },
    {
      dataIndex: 'code',
      key: 'code',
      title: '标识码',
      width: 150,
      order: 100,
    },
    {
      dataIndex: 'priority',
      key: 'priority',
      title: '权重',
      align: 'right',
      search: false,
    },
    {
      dataIndex: 'isHidden',
      key: 'isHidden',
      title: '隐藏/显示',
      valueType: 'select',
      valueEnum: () => {
        const data = new Map();
        HiddenLabelEnum.forEach((v: any) => {
          data.set(v.value, {
            text: v.label,
          });
        });
        return data;
      },
      render: (_, record) => {
        return (
          <Popconfirm
            title={`确认要${record.isHidden === HiddenEnum.True ? '显示' : '隐藏'}吗？`}
            onConfirm={() => toggleHidden(record)}
          >
            <a>
              <Tag color={record.isHidden === HiddenEnum.False ? 'green' : undefined}>
                {HiddenLabelEnum.find((v) => v.value === record.isHidden)?.label}
              </Tag>
            </a>
          </Popconfirm>
        );
      },
      align: 'center',
      order: 80,
    },
    {
      dataIndex: 'createTime',
      key: 'createTime',
      title: '创建时间',
      search: false,
      renderText: (_, record) => {
        return record.createTime
          ? moment(record.createTime * 1000).format('YY/MM/DD HH:mm')
          : undefined;
      },
      align: 'center',
    },
    {
      title: '选择操作',
      key: 'action',
      valueType: 'option',
      align: 'center',
      render: (_, record) => {
        return (
          <Space>
            <a key="add" onClick={() => add({ parentId: record.id })}>
              添加
            </a>
            <a key="edit" onClick={() => edit(record)}>
              修改
            </a>
            <TableDropdown
              key="more"
              menus={[
                {
                  key: 'share',
                  name: '分享',
                  onClick: () => handleShare(record),
                },
                {
                  key: 'del',
                  name: (
                    <Popconfirm key="del" title="确认要删除吗？" onConfirm={() => remove(record)}>
                      <a>删除</a>
                    </Popconfirm>
                  ),
                },
              ]}
            />
          </Space>
        );
      },
    },
    {
      dataIndex: 'words',
      key: 'words',
      title: '关键词',
      hideInTable: true,
    },
  ];

  const handleEditClose = () => {
    setEditor(undefined);
  };

  const handleEditSuccess = () => {
    refresh();
    handleEditClose();
  };

  const search = async (params: ASSETS.CATEGORY.AllRequest) => {
    const res = await Trees(params);
    const list = res.data?.list || [];
    return {
      data: list,
      success: true,
      total: list.length,
    };
  };

  const handleSharerClose = () => {
    setSharer(undefined);
  };

  const handleSharerSuccess = (data?: ASSETS.SHARE.CreateResponse) => {
    handleSharerClose();
    setShared(data);
  };

  const handleSharedCoese = () => {
    setShared(undefined);
  };

  return (
    <>
      <PageContainer title="资源分类">
        <ProCard title="列表">
          <ProTable<ASSETS.CATEGORY.Tree, ASSETS.CATEGORY.AllRequest>
            actionRef={table}
            rowKey="id"
            columns={columns}
            request={search}
            search={{
              defaultCollapsed: false,
            }}
            toolBarRender={() => [
              <Button key="add" type="primary" title="新增" block={true} onClick={() => add()}>
                <PlusOutlined /> 新增
              </Button>,
            ]}
            pagination={false}
          />
        </ProCard>
      </PageContainer>
      {editor && (
        <EditModule record={editor} onSuccess={handleEditSuccess} onClose={handleEditClose} />
      )}
      {sharer && (
        <ShareCreateModule
          params={sharer}
          onSuccess={handleSharerSuccess}
          onClose={handleSharerClose}
        />
      )}
      {shared && (
        <ShareSuccessModule record={shared} onOk={handleSharedCoese} onCancel={handleSharedCoese} />
      )}
    </>
  );
};

export default AssetsCategoryIndexPage;
